﻿
// DBMSDlg.cpp : 实现文件
//

#include "stdafx.h"
#include "DBMS.h"
#include "DBMSDlg.h"
#include "afxdialogex.h"
#include "CrtDbDlg.h"
#include "CrtTableDlg.h"
#include <string>
#include <fstream>
#include <vector>
#include "tool.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#define _CRT_SECURE_NO_WARNINGS

int m_row,m_col;
tool t;
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

	// 对话框数据
	enum { IDD = IDD_ABOUTBOX };

protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

	// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CDBMSDlg 对话框



CDBMSDlg::CDBMSDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(CDBMSDlg::IDD, pParent)
	, m_userName(_T(""))
	, m_password(_T(""))
	, v_ipAddr(_T(""))
{
	m_hIcon = AfxGetApp()->LoadIcon(IDI_ICON4);

}

void CDBMSDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_TREE1, m_treeCtrl);
	DDX_Control(pDX, IDC_LIST1, m_list);
	DDX_Control(pDX, IDC_BUTTON1, b_saveTable);
	DDX_Control(pDX, IDC_EDIT2, m_edit);
	DDX_Text(pDX, IDC_EDIT3, m_userName);
	DDX_Text(pDX, IDC_EDIT4, m_password);
	DDX_Control(pDX, IDC_BUTTON3, b_login);
	DDX_Control(pDX, IDC_BUTTON4, b_cancelLogin);
	DDX_Control(pDX, IDC_EDIT3, m_username);
	DDX_Control(pDX, IDC_EDIT4, m_Password);
	DDX_Control(pDX, IDC_STATIC9, m_static1);
	DDX_Control(pDX, IDC_STATIC7, m_static2);
	DDX_Control(pDX, IDC_STATIC8, m_static3);
	DDX_Control(pDX, IDC_EDIT5, m_ipAddr);
	DDX_Control(pDX, IDC_STATIC10, m_static4);
	DDX_Text(pDX, IDC_EDIT5, v_ipAddr);
}

BEGIN_MESSAGE_MAP(CDBMSDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_COMMAND(ID_32788, &CDBMSDlg::On32788)
	ON_COMMAND(ID_32784, &CDBMSDlg::On32784)
	ON_COMMAND(ID_32776, &CDBMSDlg::On32776)
	ON_COMMAND(ID_32778, &CDBMSDlg::On32778)
	ON_BN_CLICKED(IDC_BUTTON1, &CDBMSDlg::OnBnClickedButton1)
	ON_NOTIFY(TVN_SELCHANGED, IDC_TREE1, &CDBMSDlg::OnSelchangedTree1)
	ON_COMMAND(ID_32777, &CDBMSDlg::On32777)
	ON_COMMAND(ID_32780, &CDBMSDlg::On32780)
	ON_NOTIFY(NM_CLICK, IDC_TREE1, &CDBMSDlg::OnClickTree1)
	ON_COMMAND(ID_32781, &CDBMSDlg::On32781)
	ON_WM_ERASEBKGND()
	ON_COMMAND(ID_32785, &CDBMSDlg::On32785)
	ON_COMMAND(ID_32787, &CDBMSDlg::On32787)
	ON_COMMAND(ID_32783, &CDBMSDlg::On32783)
	ON_COMMAND(ID_32791, &CDBMSDlg::On32791)
	ON_NOTIFY(NM_DBLCLK, IDC_LIST1, &CDBMSDlg::OnDblclkList1)
	ON_EN_KILLFOCUS(IDC_EDIT2, &CDBMSDlg::OnKillfocusEdit2)
	ON_NOTIFY(NM_CLICK, IDC_LIST1, &CDBMSDlg::OnClickList1)
	ON_BN_CLICKED(IDC_BUTTON3, &CDBMSDlg::OnClickedButton3)
	ON_BN_CLICKED(IDC_BUTTON4, &CDBMSDlg::OnClickedButton4)
	ON_COMMAND(ID_Login, &CDBMSDlg::OnLogin)
	ON_NOTIFY(NM_DBLCLK, IDC_TREE1, &CDBMSDlg::OnDblclkTree1)
	ON_COMMAND(ID_32795, &CDBMSDlg::On32795)
END_MESSAGE_MAP()


// CDBMSDlg 消息处理程序

BOOL CDBMSDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码 
	menu.LoadMenu(IDR_MENU1);  //IDR_MENU1为菜单栏ID号  
	SetMenu(&menu);  

	counter1=0;
	counter2=0;
	counter3=0;
	m_treeFlag=1;
	treeFlag2=1;//1是创建数据库 0是表
	flag=0;
	insertRecordFlag=0;//1是插入记录 在保存按钮响应用到
	insertFieldFlag=0;//1是插入字段 在保存按钮响应用到
	modRcdFlag=0;
	isFirstTime=false;//true为建表时的添加字段，false为添加字段
	fieldNum=0;
	dbClickeddatabase=0;
	addDb=true;
	rowCount=-1;

	m_list.ModifyStyle(0,LVS_REPORT);//报表模式
	m_list.SetExtendedStyle(m_list.GetExtendedStyle()|LVS_EX_GRIDLINES|LVS_EX_FULLROWSELECT| WS_CLIPSIBLINGS);//间隔线+行选中

	HICON hIcon[2];
	hIcon[0]=theApp.LoadIcon(IDI_ICON1);
	hIcon[1]=theApp.LoadIcon(IDI_ICON2);

	iList.Create(32,32,ILC_COLOR32,3,3);
	iList.Add(hIcon[0]);
	iList.Add(hIcon[1]);

	m_treeCtrl.SetImageList(&iList,TVSIL_NORMAL);

	m_list.ShowWindow(SW_HIDE);
	b_saveTable.ShowWindow(SW_HIDE);
	m_edit.ShowWindow(SW_HIDE);
	m_treeCtrl.ShowWindow(SW_HIDE);
	m_static1.ShowWindow(SW_HIDE);
	m_static2.ShowWindow(SW_HIDE);
	m_static3.ShowWindow(SW_HIDE);
	m_static4.ShowWindow(SW_HIDE);
	m_username.ShowWindow(SW_HIDE);
	m_Password.ShowWindow(SW_HIDE);
	m_ipAddr.ShowWindow(SW_HIDE);
	b_login.ShowWindow(SW_HIDE);
	b_cancelLogin.ShowWindow(SW_HIDE);

	

	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CDBMSDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CDBMSDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CDBMSDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

//帮助
void CDBMSDlg::On32788()
{
	// TODO: 在此添加命令处理程序代码
	system("start explorer http://gougouchat.cn/doc/"); 
}


//字符串分隔
void CDBMSDlg::Split(CString source, CStringArray& dest, char division)  
{  
	dest.RemoveAll();  
	int i;  
	for (i = 0; i < source.GetLength(); i ++)  
	{  
		if (source.GetAt(i) == division)  
		{  
			dest.Add(source.Left(i)); //remove left  
			for (int j = 0; j < (dest.GetSize() - 1); j ++)  
			{  
				dest[dest.GetSize()-1] = dest[dest.GetSize()-1].Right(dest[dest.GetSize()-1].GetLength()-dest[j].GetLength()-1);  //remove right  
			}  
		}  
	}  

	dest.Add(source.Left(i));  
	for (int j = 0; j < (dest.GetSize() - 1); j ++)  
	{  
		dest[dest.GetSize()-1] = dest[dest.GetSize()-1].Right(dest[dest.GetSize()-1].GetLength()-dest[j].GetLength()-1);  
	}  

}


//CString转化为string
string CDBMSDlg::Transfer(CString a){
	USES_CONVERSION;
	string b(W2A(a));
	return b;
}

//CString转化为int
int CDBMSDlg::Transfer1(CString a){
	int b;
	b=_tstoi(a);
	return b;
}

//int转化为CString
CString CDBMSDlg::Transfer3(int a){
	CString b;
	char c[10];
	sprintf_s(c,10,"%d",a);
	b=c;
	return b;
}

//获得现在所选节点并存到strText里
void CDBMSDlg::OnSelchangedTree1(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);
	//NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;  
	hItem = m_treeCtrl.GetSelectedItem();  //当前所选节点 

	if(hItem != NULL)  
	{  
		CString strText= m_treeCtrl.GetItemText(hItem);//获取节点文本  
	}  

	// TODO: 在此添加控件通知处理程序代码
	*pResult = 0;
}

//树获取鼠标
void CDBMSDlg::OnClickTree1(NMHDR *pNMHDR, LRESULT *pResult)
{
	// TODO: 在此添加控件通知处理程序代码
	CPoint point;
	GetCursorPos(&point);//获得鼠标点击的位置
	m_treeCtrl.ScreenToClient(&point);//转化为客户坐标
	UINT uFlags;

	HTREEITEM CurrentItem;
	CurrentItem=m_treeCtrl.HitTest(point,&uFlags);//获得当前点击节点的ITEM
	//获得该节点的父节点
	currentNode=m_treeCtrl.GetItemText(CurrentItem) ;//获得节点值
	*pResult = 0;
}

BOOL CDBMSDlg::OnEraseBkgnd(CDC* pDC)
{
	// TODO: 在此添加消息处理程序代码和/或调用默认值

	return CDialogEx::OnEraseBkgnd(pDC);
}

//插入记录 listCtrl可编辑
void CDBMSDlg::OnDblclkList1(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
	CRect rc;
	m_row = pNMItemActivate->iItem;//获得选中的行  
	m_col = pNMItemActivate->iSubItem;//获得选中列  
	m_list.GetSubItemRect(m_row,m_col,LVIR_LABEL,rc);//获得子项的RECT；  
	m_edit.SetParent(&m_list);//转换坐标为列表框中的坐标  
	m_edit.MoveWindow(rc);//移动Edit到RECT坐在的位置;  
	m_edit.SetWindowText(m_list.GetItemText(m_row,m_col));//将该子项中的值放在Edit控件中；  
	m_edit.ShowWindow(SW_SHOW);//显示Edit控件；  
	m_edit.SetFocus();//设置Edit焦点  
	m_edit.ShowCaret();//显示光标  
	m_edit.SetSel(-1);//将光标移动到最后  
	*pResult = 0;
}
void CDBMSDlg::OnKillfocusEdit2()
{
	// TODO: 在此添加控件通知处理程序代码
	CString tem; 

	int nIndex = m_list.GetItemCount();
	m_list.InsertItem(nIndex,_T(""));

	m_edit.GetWindowText(tem);    //得到用户输入的新的内容  
	m_list.SetItemText(m_row,m_col,tem);   //设置编辑框的新内容  
	m_edit.ShowWindow(SW_HIDE);                //应藏编辑框 
}


//告诉后台双击了哪个数据库
void CDBMSDlg::ShowDbClickedDatabase(CString msg){

	if(msg.Compare(_T("success"))==0){
		request=_T("showTables");
		CString sql;
		sql=_T("show tables");
		SendSQL(sql);
		request=_T("");
	}
	else
		AfxMessageBox(msg);
}

//将接受到的表名显示在树上对应的数据库下
void CDBMSDlg::ShowTreeT(CString msg){
	CStringArray dest;
	int images=1;
	Split(msg,dest,'\n');

	for(int i=0;i<dest.GetSize()-1;i++){
		hItem=m_treeCtrl.GetSelectedItem();//设置选中为双击的数据库
		TVINSERTSTRUCT ts={0};//节点数据
		ts.hParent=hItem;//新节点的父节点
		ts.hInsertAfter=TVI_LAST;//加在同级节点最后
		ts.item.pszText=(LPTSTR)(LPCTSTR)dest[i];
		ts.item.mask=TVIF_TEXT;//让文本成员有效
		HTREEITEM hNewItem=m_treeCtrl.InsertItem(ts.item.pszText,images,images,ts.hParent,ts.hInsertAfter);

		m_treeCtrl.EnsureVisible(hNewItem);//确保新节点在可视范围内
	}
}

//将接受到的数据库名 表名显示在树上
void CDBMSDlg::ShowTreeD(CString msg){
	CStringArray dest;
	int images=0;
	Split(msg,dest,'\n');

	for(int i=0;i<dest.GetSize()-1;i++){
		hItem=TVI_ROOT;
		TVINSERTSTRUCT ts={0};//节点数据
		ts.hParent=hItem;//新节点的父节点
		ts.hInsertAfter=TVI_LAST;//加在同级节点最后
		ts.item.pszText=(LPTSTR)(LPCTSTR)dest[i];
		ts.item.mask=TVIF_TEXT;//让文本成员有效
		HTREEITEM hNewItem=m_treeCtrl.InsertItem(ts.item.pszText,images,images,ts.hParent,ts.hInsertAfter);

		m_treeCtrl.EnsureVisible(hNewItem);//确保新节点在可视范围内
	}
}

//弹出设置数据库或表名 添加树节点 treeFlag2表是0 数据库是1
CString CDBMSDlg::AddTree(){
	CString newName;
	int images=1;
	CrtDbDlg cDlg;
	TVINSERTSTRUCT ts={0};//节点数据
	INT_PTR nResponse = cDlg.DoModal();

	if(nResponse==IDOK){
		newName=cDlg.v_newDbName;
	}
	else{
		m_treeFlag=0;
		treeFlag2=0;
		return NULL;
	}

	hItem=m_treeCtrl.GetSelectedItem();//当前所选节点
	if((hItem==NULL&&addDb)||(m_treeFlag==1&&addDb)){
		//SQL
		CString sql;
		sql.Append(_T("create "));
		sql.Append(_T("database "));
		sql.Append(newName);
		SendSQL(sql);	

		images=0;
		m_treeFlag=0;
		hItem=TVI_ROOT;
	}

	ts.hParent=hItem;//新节点的父节点
	ts.hInsertAfter=TVI_LAST;//加在同级节点最后
	ts.item.pszText=(LPTSTR)(LPCTSTR)newName;
	ts.item.mask=TVIF_TEXT;//让文本成员有效
	HTREEITEM hNewItem=m_treeCtrl.InsertItem(ts.item.pszText,images,images,ts.hParent,ts.hInsertAfter);//添加新节点

	if(hItem==TVI_ROOT)
		m_treeCtrl.SelectItem(hNewItem);//选中新节点--根节点
	else
		m_treeCtrl.SelectItem(ts.hParent);//选中当前数据库节点

	m_treeCtrl.EnsureVisible(hNewItem);//确保新节点在可视范围内
	counter1=0;

	//弹出对话框保存名字时
	//如果是表YES，返回当前输入名字供文件名用
	//如果是数据库YES，先不保存文件
	if(treeFlag2==0)
		return newName;
	else
		return NULL;

}

//登录时的退出
void CDBMSDlg::OnClickedButton4()
{
	// TODO: 在此添加控件通知处理程序代码
	SendMessage(WM_CLOSE);
}

//双击树
void CDBMSDlg::OnDblclkTree1(NMHDR *pNMHDR, LRESULT *pResult)
{
	m_list.ShowWindow(SW_SHOW);
	b_saveTable.ShowWindow(SW_SHOW);
	m_treeCtrl.ShowWindow(SW_SHOW);
	m_static1.ShowWindow(SW_HIDE);
	m_static2.ShowWindow(SW_HIDE);
	m_static3.ShowWindow(SW_HIDE);
	m_static4.ShowWindow(SW_HIDE);
	m_username.ShowWindow(SW_HIDE);
	m_Password.ShowWindow(SW_HIDE);
	m_ipAddr.ShowWindow(SW_HIDE);
	b_login.ShowWindow(SW_HIDE);
	b_cancelLogin.ShowWindow(SW_HIDE);
	// TODO: 在此添加控件通知处理程序代码
	*pResult = 1;
	hItem=m_treeCtrl.GetSelectedItem();//当前所选节点

	//双击表
	if((hItem!=NULL)&&(GetTreeLevel(hItem)==2)){//判断结点是否有子结点
		CString sql;
		sql.Append(_T("select * from "));
		sql.Append(currentNode);
		//AfxMessageBox(sql);
		request=_T("ShowDbClickedTable");
		SendSQL(sql);
		request=_T("");
	}
	//双击数据库
	else if(GetTreeLevel(hItem)==1){

		if(currentNode.Compare(preNode)!=0||dbClickeddatabase==0){
			CString sql;
			sql.Append(_T("use "));
			sql.Append(currentNode);
			preNode=currentNode;
			request=_T("ShowDbClickedDatabase");
			SendSQL(sql);
			dbClickeddatabase++;
			request=_T("");
		}
	}
}

//判断选择节点层次
int CDBMSDlg::GetTreeLevel(HTREEITEM item){
	int level=0;
	HTREEITEM temp;
	temp=item;
	while(temp!=NULL){
		temp=m_treeCtrl.GetParentItem(temp);
		++level;
	}
	return level;
}


//确认登录
void CDBMSDlg::OnClickedButton3()
{
	//网络初始化
	CString a;
	m_ipAddr.GetWindowText(a);
	mPro=new MessagePro(a,8080);
	mPro->Init();

	CString userName,password,sql;
	m_username.GetWindowText(userName);
	m_Password.GetWindowText(password);

	sql.Append(userName);
	sql.Append(_T("|"));
	sql.Append(password);
	request=_T("login");
	SendSQL(sql);
	request=_T("");
	menu.EnableMenuItem(ID_Login,MF_GRAYED);
}

//系统——用户登录
void CDBMSDlg::OnLogin()
{
	// TODO: 在此添加命令处理程序代码
	m_static1.ShowWindow(SW_SHOW);
	m_static2.ShowWindow(SW_SHOW);
	m_static3.ShowWindow(SW_SHOW);
	m_static4.ShowWindow(SW_SHOW);
	m_username.ShowWindow(SW_SHOW);
	m_Password.ShowWindow(SW_SHOW);
	m_ipAddr.ShowWindow(SW_SHOW);
	b_login.ShowWindow(SW_SHOW);
	b_cancelLogin.ShowWindow(SW_SHOW);
}

//登录成功请求显示数据库
void CDBMSDlg::LoginSuccess(){
	m_list.ShowWindow(SW_SHOW);
	b_saveTable.ShowWindow(SW_SHOW);
	m_treeCtrl.ShowWindow(SW_SHOW);
	m_static1.ShowWindow(SW_HIDE);
	m_static2.ShowWindow(SW_HIDE);
	m_static3.ShowWindow(SW_HIDE);
	m_static4.ShowWindow(SW_HIDE);
	m_ipAddr.ShowWindow(SW_HIDE);
	m_username.ShowWindow(SW_HIDE);
	m_Password.ShowWindow(SW_HIDE);
	b_login.ShowWindow(SW_HIDE);
	b_cancelLogin.ShowWindow(SW_HIDE);

	
	CString sql;
	request=_T("showDatabases");
	sql=_T("show databases");
	SendSQL(sql);
	request=_T("");
}


//创建数据库
void CDBMSDlg::On32776()
{
	m_treeFlag=1;
	treeFlag2=1;
	// TODO: 在此添加命令处理程序代码
	m_list.ShowWindow(SW_HIDE);
	b_saveTable.ShowWindow(SW_HIDE);
	m_treeCtrl.ShowWindow(SW_SHOW);
	m_static1.ShowWindow(SW_HIDE);
	m_static2.ShowWindow(SW_HIDE);
	m_static3.ShowWindow(SW_HIDE);
	m_static4.ShowWindow(SW_HIDE);
	m_ipAddr.ShowWindow(SW_HIDE);
	m_username.ShowWindow(SW_HIDE);
	m_Password.ShowWindow(SW_HIDE);
	b_login.ShowWindow(SW_HIDE);
	b_cancelLogin.ShowWindow(SW_HIDE);

	request=_T("createDatabase");
	AddTree();

}

//删除数据库
void CDBMSDlg::On32777()
{
	m_treeCtrl.ShowWindow(SW_SHOW);
	// TODO: 在此添加命令处理程序代码
	hItem = m_treeCtrl.GetSelectedItem(); //当前所选节点 
	if(counter3==0){
		AfxMessageBox(_T("请选择一个数据库!")); 
		counter3++;
		return;
	}
	m="确定删除数据库 ";
	m.Append(currentNode);
	m.Append(_T(" 吗？\n这样会导致该数据库下所有表被删除"));
	INT_PTR nRes=AfxMessageBox(m,MB_YESNO|MB_ICONQUESTION);
	if(nRes==IDYES){
		//SQL
		CString sql;
		sql.Append(_T("drop "));
		sql.Append(_T("database "));
		sql.Append(currentNode);
		request=_T("dropDatabase");
		SendSQL(sql);
		request=_T("");
		HTREEITEM hParent = m_treeCtrl.GetParentItem(hItem); //取得当前节点的父节点   
		m_treeCtrl.DeleteItem(hItem); //删除节点 
		m_treeCtrl.SelectItem(hParent);//选中其父节点
		counter3=0;

	}
	else{
		counter3=0;
		return;
	}
}

//删除表
void CDBMSDlg::On32780()
{
	m_treeCtrl.ShowWindow(SW_SHOW);
	// TODO: 在此添加命令处理程序代码
	hItem = m_treeCtrl.GetSelectedItem(); //当前所选节点 
	if(counter2==0){
		AfxMessageBox(_T("请选择一个表!")); 
		counter2++;
		return;
	}
	m="确定删除表 ";
	m.Append(currentNode);
	m.Append(_T(" 吗？"));
	INT_PTR nRes=AfxMessageBox(m,MB_YESNO|MB_ICONQUESTION);
	if(nRes==IDYES){
		//SQL
		CString sql;
		sql.Append(_T("drop "));
		sql.Append(_T("table "));
		sql.Append(currentNode);
		request=_T("dropTable");
		SendSQL(sql);
		request=_T("");
		HTREEITEM hParent = m_treeCtrl.GetParentItem(hItem); //取得当前节点的父节点   
		m_treeCtrl.DeleteItem(hItem); //删除节点 
		m_treeCtrl.SelectItem(hParent);//选中其父节点
		counter2=0;

	}
	else{
		counter2=0;
		return;
	}
}

//创建表
void CDBMSDlg::On32778()
{
	ClearList();
	// TODO: 在此添加命令处理程序代码
	m_list.ShowWindow(SW_SHOW);
	b_saveTable.ShowWindow(SW_SHOW);
	m_treeCtrl.ShowWindow(SW_SHOW);
	m_static1.ShowWindow(SW_HIDE);
	m_static2.ShowWindow(SW_HIDE);
	m_static3.ShowWindow(SW_HIDE);
	m_static4.ShowWindow(SW_HIDE);
	m_ipAddr.ShowWindow(SW_HIDE);
	m_username.ShowWindow(SW_HIDE);
	m_Password.ShowWindow(SW_HIDE);
	b_login.ShowWindow(SW_HIDE);
	b_cancelLogin.ShowWindow(SW_HIDE);

	m_list.DeleteAllItems();
	m_list.DeleteColumn(0);

	isFirstTime=true;
	InitTable();
	CrtTable();
}

//显示初始表 创建表时
void CDBMSDlg::InitTable(){

	CRect rect;
	GetClientRect(&rect);

	m_list.InsertColumn(0,_T("字段名"));
	m_list.InsertColumn(1,_T("类型"));
	m_list.InsertColumn(2,_T("长度"));
	m_list.InsertColumn(3,_T("主键"));
	m_list.InsertColumn(4,_T("不为空"));
	m_list.InsertColumn(5,_T("唯一"));

	m_list.SetColumnWidth(0,rect.Width()/8);
	m_list.SetColumnWidth(1,rect.Width()/8);
	m_list.SetColumnWidth(2,rect.Width()/8);
	m_list.SetColumnWidth(3,rect.Width()/8);
	m_list.SetColumnWidth(4,rect.Width()/8);
	m_list.SetColumnWidth(5,rect.Width()/8);
}


//保存第一次建的表
void CDBMSDlg::SaveNewTable(CString tableName){
	//得到字段名不为空的字段数
	for(int i=0;i<20;i++){
		CString a=m_list.GetItemText(i,0);
		if((m_list.GetItemText(i,0).Compare(_T("")))!=0)
			fieldNum++;
		else;
	}

	CString sql;
	sql.Append(_T("create table "));
	sql.Append(tableName);
	sql.Append(_T("("));

	for(int i=0;i<fieldNum;i++){
		for(int j=0;j<6;j++){
			if(j==1||j==0){
				sql.Append(_T(" "));
				sql.Append(m_list.GetItemText(i,j));
			}

			//长度
			if(j==2){
				if(m_list.GetItemText(i,j-1).Compare(_T("varchar"))==0){
					sql.Append(_T("("));
					sql.Append(m_list.GetItemText(i,j));
					sql.Append(_T(")"));
				}else;
			}
			//主键
			if(j==3){
				if(m_list.GetItemText(i,j).Compare(_T("否"))==0);
				else if(m_list.GetItemText(i,j).Compare(_T("是"))==0){
					sql.Append(_T(" primary key "));
				}
			}
			//不为空
			if(j==4){
				if(m_list.GetItemText(i,j).Compare(_T("否"))==0);
				else if(m_list.GetItemText(i,j).Compare(_T("是"))==0){
					sql.Append(_T(" not null "));
				}
			}
			//唯一
			if(j==5){
				if(m_list.GetItemText(i,j).Compare(_T("否"))==0);
				else if(m_list.GetItemText(i,j).Compare(_T("是"))==0){
					sql.Append(_T(" unique "));
				}
			}
		}
		if(i!=fieldNum-1)
			sql.Append(_T(","));
	}		

	sql.Append(_T(")"));
	CString sql1;
	sql1=_T("use ");
	sql1.Append(currentNode);
	SendSQL(sql1);
	request=_T("createTable");
	SendSQL(sql);
	request=_T("");
}

//删除记录
void CDBMSDlg::On32787()
{

	if(m_list.GetNextItem(-1,LVNI_ALL | LVNI_SELECTED) != -1)
	{
		int nItem = m_list.GetNextItem(-1,LVNI_ALL | LVNI_SELECTED);
		m="确定要删除该记录吗？";
		INT_PTR nRes=AfxMessageBox(m,MB_YESNO|MB_ICONQUESTION);
		if(nRes==IDYES){
			CString sql;
			sql.Append(_T("delete from "));
			sql.Append(currentNode);
			sql.Append(_T(" where "));

			//获取列标题
			LVCOLUMN lvcol;
			char  str[256];
			lvcol.mask = LVCF_TEXT;
			lvcol.pszText = (LPWSTR)str;
			lvcol.cchTextMax = 256;
			m_list.GetColumn(0, &lvcol);

			sql.Append(lvcol.pszText);
			sql.Append(_T("="));

			CString a;
			a=trimAll(Transfer(m_list.GetItemText(nItem,0)),"\n").c_str();
			sql.Append(a);
			request=_T("");
			SendSQL(sql);
			m_list.DeleteItem(nItem);
		}
		else return;
	}else{
		m="请选择一个要删除的记录!";
		AfxMessageBox(m,MB_ICONWARNING);
	}
}

//清空表格中的现有内容
void CDBMSDlg::ClearList(){
	int nColumnCount = m_list.GetHeaderCtrl()->GetItemCount();
	for(int i=0;i<nColumnCount;i++)
		m_list.DeleteColumn(0);
	m_list.DeleteAllItems();
	m_list.SetRedraw(TRUE);
	m_list.Invalidate();
	m_list.UpdateWindow();
}

//双击表格时 显示发回的表格内容 
void CDBMSDlg::ShowDbClickTable(CString msg){
	ClearList();

	CRect rect;
	GetClientRect(&rect);

	CStringArray dest1,dest2;//dest1承接行 dest2承接每行数据
	Split(msg,dest1,'| \r\n');
	for(int i=0;i<dest1.GetSize()-1;i++){		
		Split(dest1[i],dest2,'|');
		if(i==0)//表头 字段
			for(int j=0;j<dest2.GetSize()-1;j++){
				m_list.InsertColumn(j,dest2[j]);
				m_list.SetColumnWidth(j,rect.Width()/dest2.GetSize());
			}
		else{//记录
			int row;
			row=m_list.InsertItem(i,dest2[0]);
			for(int j=0;j<dest2.GetSize();j++){
				m_list.SetItemText(row,j,dest2[j]);
			}
		}
		rowCount++;
	}
	fields=dest1[0];
	m_list.SetRedraw(TRUE);
	m_list.Invalidate();
	m_list.UpdateWindow();
}

//插入记录
void CDBMSDlg::On32784()
{
	// TODO: 在此添加命令处理程序代码

	flag++;
	insertRecordFlag++;
}

//保存插入的记录
void CDBMSDlg::SaveNewRecord(){
	CString sql;
	int recordNum=0;
	int fieldNum1 = m_list.GetHeaderCtrl()->GetItemCount();

	//得到字段名不为空的记录数
	for(int i=0;i<20;i++){
		if((m_list.GetItemText(i,0).Compare(_T("")))!=0)
			recordNum++;
		else;
	}
	int newRecord=recordNum-rowCount;

	CStringArray f;
	Split(fields,f,'|');

	for(int i=recordNum-1;i>rowCount-1;i--){
		sql.Append(_T("insert into "));
		sql.Append(currentNode);
		sql.Append(_T("("));
		for(int k=0;k<fieldNum1;k++){
			sql.Append(f[k]);
			if(k<fieldNum1-1)
				sql.Append(_T(","));
		}
		sql.Append(_T(") values("));

		for(int j=0;j<fieldNum1;j++){
			sql.Append(m_list.GetItemText(i,j));
			if(j<fieldNum1-1)
				sql.Append(_T(","));
		}
		sql.Append(_T(")"));
		request=_T("insertRecord");
		SendSQL(sql);
		request=_T("");
	}
}

//更新记录
void CDBMSDlg::On32785()
{
	modRcdFlag++;
}

//更新记录时(先单击后双击) 对列表的单击事件响应
void CDBMSDlg::OnClickList1(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
	int fieldNum2 = m_list.GetHeaderCtrl()->GetItemCount();

	if(modRcdFlag!=0){
		int nItem;
		CString old1;
		CStringArray dest;

		//得到单击之后的行原来的数据
		nItem = m_list.GetNextItem(-1,LVNI_ALL | LVNI_SELECTED);

		for(int j=0;j<fieldNum2;j++){
			old1.Append(m_list.GetItemText(nItem,j));
			if(j<fieldNum2-1)
				old1.Append(_T("$"));
		}

		t.beforeModRcd=old1;
		t.row1=nItem;
	}
	*pResult = 0;
}

//在表上修改了之后保存按钮之后
void CDBMSDlg::SaveModRcd(){	
	int fieldNum2 = m_list.GetHeaderCtrl()->GetItemCount();
	int i=0;
	int nItem;
	CString old1,newRcd,sql;
	CStringArray dest;
	old1=t.beforeModRcd;
	nItem=t.row1;

	Split(old1,dest,'$');
	sql.Append(_T("update "));
	sql.Append(currentNode);
	sql.Append(_T(" set "));
	for(int j=0;j<fieldNum2;j++){
		if(dest[j].Compare(m_list.GetItemText(nItem,j))!=0){
			newRcd=m_list.GetItemText(nItem,j);
			//获取列标题
			LVCOLUMN lvcol;
			char  str[256];
			lvcol.mask = LVCF_TEXT;
			lvcol.pszText = (LPWSTR)str;
			lvcol.cchTextMax = 256;
			m_list.GetColumn(j, &lvcol);

			sql.Append(lvcol.pszText);
			sql.Append(_T("="));
			sql.Append(newRcd);
			sql.Append(_T("where "));

			m_list.GetColumn(0,&lvcol);
			sql.Append(lvcol.pszText);
			sql.Append(_T("="));
			sql.Append(dest[0]);

			SendSQL(sql);
		}
		else;
	}
}

//删除字段
void CDBMSDlg::On32783()
{
	if(m_list.GetNextItem(-1,LVNI_ALL | LVNI_SELECTED) != -1)
	{
		int nItem = m_list.GetNextItem(-1,LVNI_ALL | LVNI_SELECTED);
		m="确定要删除该字段吗？";
		INT_PTR nRes=AfxMessageBox(m,MB_YESNO|MB_ICONQUESTION);
		if(nRes==IDYES){

			//SQL
			CString sql;
			sql.Append(_T("alter table "));
			sql.Append(currentNode);
			sql.Append(_T(" drop "));

			CString a;
			a=trimAll(Transfer(m_list.GetItemText(nItem,0)),"\n").c_str();
			sql.Append(a);

			SendSQL(sql);

			m_list.DeleteItem(nItem);
		}else return;
	}else{
		m="请选择一个要删除的字段!";
		AfxMessageBox(m,MB_ICONWARNING);
	}
}

//修改字段 只能修改varchar大小
void CDBMSDlg::On32791()
{
	AfxMessageBox(_T("只能变化varchar类型字段的长度喔～"));
	// TODO: 在此添加命令处理程序代码
	if(m_list.GetNextItem(-1,LVNI_ALL | LVNI_SELECTED) != -1)
	{
		CString sql;
		BOOL b_varchar=false;
		CrtTableDlg tDlg;
		int nItem = m_list.GetNextItem(-1,LVNI_ALL | LVNI_SELECTED);
		CString temp=m_list.GetItemText(nItem,0);
		tDlg.setText(temp);

		if(m_list.GetItemText(nItem,1).Compare(_T("varchar"))==0)
			b_varchar=true;//原来类型是varchar

		INT_PTR nResponce=tDlg.DoModal();		

		if(nResponce==IDOK){
			sql.Append(_T("alter table "));
			sql.Append(currentNode);
			sql.Append(_T(" modify "));

			CString a;
			a=trimAll(Transfer(m_list.GetItemText(nItem,0)),"\n").c_str();
			sql.Append(a);

			sql.Append(_T(" "));
			sql.Append(tDlg.v_crtTFieldType);

			if(tDlg.v_fieldLength.Compare(_T(""))!=0){
				m_list.SetItemText(nItem,2,tDlg.v_fieldLength);
				sql.Append(_T("("));
				sql.Append(tDlg.v_fieldLength);
				sql.Append(_T(") "));
			}			
		}
		if(b_varchar&&tDlg.v_crtTFieldType!=_T("varchar"))
			m_list.SetItemText(nItem,2,_T("0"));
		m_list.SetItemText(nItem,1,tDlg.v_crtTFieldType);

		SendSQL(sql);
	}else{
		m="请选择一个要修改的字段!";
		AfxMessageBox(m,MB_ICONWARNING);
	}
}

//添加字段
void CDBMSDlg::On32781()
{
	// TODO: 在此添加命令处理程序代码	
	insertFieldFlag++;
	CrtTable();
}

//弹出字段属性对话框
void CDBMSDlg::CrtTable(){
	CrtTableDlg tDlg;
	INT_PTR nResponce=tDlg.DoModal();
	CString fieldName,fieldType;
	BOOL primary,notnull,unique;
	CString sprimary,snotnull,sunique;
	int fieldLength;

	if(nResponce==IDOK){
		fieldName=tDlg.v_crtTFieldName;
		fieldType=tDlg.v_crtTFieldType;
		CString a=tDlg.v_fieldLength;
		fieldLength=Transfer1(a);
		primary=tDlg.v_primary;
		notnull=tDlg.v_notNull;
		unique=tDlg.v_unique;
	}else return;

	if(primary) sprimary=_T("是");
	else sprimary=_T("否");
	if(notnull) snotnull=_T("是");
	else snotnull=_T("否");
	if(unique) sunique=_T("是");
	else sunique=_T("否");

	int i = m_list.GetItemCount();//获取list里面有多少行 
	int nRow = m_list.InsertItem(i+1,fieldName);//插入行
	m_list.SetItemText(nRow,1,fieldType);//设置数据
	m_list.SetItemText(nRow,2,Transfer3(fieldLength));
	m_list.SetItemText(nRow,3,sprimary);
	m_list.SetItemText(nRow,4,snotnull);
	m_list.SetItemText(nRow,5,sunique);

	m_list.SetRedraw(TRUE);
	m_list.Invalidate();
	m_list.UpdateWindow();
}

//保存插入的字段
void CDBMSDlg::SaveNewField(){
	m_list.SetRedraw(TRUE);
	m_list.Invalidate();
	m_list.UpdateWindow();

	int fieldNum3 = m_list.GetHeaderCtrl()->GetItemCount();
	
	int a=m_list.GetItemCount();

	//添加到列表的最后一条字段，可视为新插入的记录
	CString sql;
	sql.Append(_T("alter table "));
	sql.Append(currentNode);
	sql.Append(_T(" add "));
	for(int i=0;i<3;i++){
		if(i==2&&m_list.GetItemText(a-1,i-1).Compare(_T("varchar"))==0){
			sql.Append(_T("("));
			sql.Append(m_list.GetItemText(a-1,i));
			sql.Append(_T(")"));
		}
		else{
		sql.Append(_T(" "));
		sql.Append(m_list.GetItemText(a-1,i));		
		}
	}
	if(m_list.GetItemText(a-1,3).Compare(_T("是"))==0)
		sql.Append(_T("primary key "));
	else;
	if(m_list.GetItemText(a-1,4).Compare(_T("是"))==0)
		sql.Append(_T("not null "));
	else;
	if(m_list.GetItemText(a-1,5).Compare(_T("是"))==0)
		sql.Append(_T("unique "));
	else;

	SendSQL(sql);
	AfxMessageBox(_T("保存字段成功！"));
}

//查看字段
void CDBMSDlg::On32795()
{
	// TODO: 在此添加命令处理程序代码
	CString sql;
	sql.Append(_T("desc "));
	sql.Append(currentNode);
	request=_T("qryField");
	SendSQL(sql);
	request=_T("");
}

//接收返回的字段信息
void CDBMSDlg::QryField(CString msg){
	ClearList();
	InitTable();

	CStringArray dest1;//dest1承接行
	Split(msg,dest1,'\r\n');
	for(int i=0;i<dest1.GetSize()-1;i++){
		Table_Field tdf=getFieldInfo(CStringTostring(dest1[i]));
		CString  a,b;
		a=tdf.name.c_str();
		b=tdf.type.c_str();

		int row=m_list.InsertItem(i,a);
		m_list.SetItemText(row,0,a);
		m_list.SetItemText(row,1,b);
		m_list.SetItemText(row,2,Transfer3(tdf.lenth));
		m_list.SetItemText(row,3,tdf.isKey);
		m_list.SetItemText(row,4,tdf.isNull);
		m_list.SetItemText(row,5,tdf.isUnique);
	}

	m_list.SetRedraw(TRUE);
	m_list.Invalidate();
	m_list.UpdateWindow();
}


//保存表0 新字段 记录 更新的记录
void CDBMSDlg::OnBnClickedButton1()
{
	CString tableName;
	CString content;
	treeFlag2=0;
	if(insertRecordFlag==0&&counter1==0&&isFirstTime){
		m="确定该表保存在当前数据库下嘛？";
		INT_PTR nRes=AfxMessageBox(m,MB_YESNO|MB_ICONQUESTION);
		if(nRes==IDYES&&counter1==0){
			addDb=false;
			tableName=AddTree();
			SaveNewTable(tableName);
			isFirstTime=FALSE;
		}
		else if(nRes==IDNO&&counter1==0){
			m="请选择数据库";
			AfxMessageBox(m);
			counter1++;
			return;
		}
	}
	else if(insertRecordFlag==0&&insertFieldFlag==0&&counter1!=0){
		tableName=AddTree();
	}
	//插入记录保存
	else if(insertRecordFlag!=0){
		SaveNewRecord();
		insertRecordFlag=0;
	}	
	//更新记录保存
	else if(!isFirstTime&&modRcdFlag!=0){
		SaveModRcd();
		modRcdFlag=0;
	}
	//字段保存
	else if(!isFirstTime&&modRcdFlag==0){
		SaveNewField();
		insertFieldFlag=0;
	}
}


//网络发送SQL语句方法
void CDBMSDlg::SendSQL(CString Sql){
	mPro->SendMsg(Transfer(Sql).c_str());

	string a="";
	CString msg;
	if(mPro->ReceiveMsg(a)){
		msg=a.c_str();	

		if(request.Compare(_T("login"))==0)
			if(msg.Compare(_T("serName or password is not correct !"))==0)
				AfxMessageBox(_T("用户名或密码错误！"));
			else{
				AfxMessageBox(_T("登录成功！"));
				LoginSuccess();
			}
			if(request.Compare(_T("showDatabases"))==0)//show databases
				ShowTreeD(msg);
			if(request.Compare(_T("ShowDbClickedDatabase"))==0)//use x 
				ShowDbClickedDatabase(msg);
			if(request.Compare(_T("showTables"))==0)//show tables
				ShowTreeT(msg);
			if(request.Compare(_T("ShowDbClickedTable"))==0)//select * from y
				ShowDbClickTable(msg);
			if(request.Compare(_T("createDatabase"))==0)//create database a
				if(msg.Compare(_T("success"))==0)
					AfxMessageBox(_T("创建数据库成功"));
				else
					AfxMessageBox(msg);
			if(request.Compare(_T("dropDatabase"))==0)//drop database a
				if(msg.Compare(_T("success"))==0)
					AfxMessageBox(_T("删除数据库成功"));
				else
					AfxMessageBox(msg);
			if(request.Compare(_T("createTable"))==0)//create table b()
				if(msg.Compare(_T("success"))==0){
					AfxMessageBox(_T("创建表成功"));
				}
				else
					AfxMessageBox(msg);
			if(request.Compare(_T("dropTable"))==0)//drop table b
				if(msg.Compare(_T("success"))==0)
					AfxMessageBox(_T("删除表成功"));
				else
					AfxMessageBox(msg);
			if(request.Compare(_T("insertRecord"))==0)//insert into a(,) values(,)
				if(msg.Compare(_T("success"))==0)
					AfxMessageBox(_T("插入成功"));
				else
					AfxMessageBox(msg);
			if(request.Compare(_T("qryField"))==0)//desc b
				QryField(msg);
	}
}

